var ClassForm = function () {
  var template = /* html */ `
    <div class="class-form" v-loading.fullscreen.lock="loading">
      <template v-if="classesForm!==null">
        <el-form label-width="auto" size="medium">
          <el-form-item label="班次名称">
            <el-input v-model="classesForm.className" placeholder="最多10个字符（中英文或数字）" :maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="上下班次数">
            <el-radio-group v-model="classesForm.timeType" @change="timeTypeChange">
              <el-radio v-for="timeWay in timeWayList" :key="'timeWay_'+timeWay.type" :label="timeWay.type">
                {{timeWay.name}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="attendance-classes-way">
          <template v-for="(timeObj,index) in classesForm.timeList">
            <div class="classes-way-item" :key="'time_'+index">
              <div style="width:60px;margin-right:30px" class="text">
                第{{index+1}}次
              </div>
              <div class="text">上班:</div>
              <div>
                <el-time-picker class="time-input" size="medium" v-model="timeObj.startTime" format="HH:mm" :picker-options="{selectableRange:timeObj.startTimeRange}" 
                  :clearable="false" :editable="false" @change="timeChange('startTime',index)">
                </el-time-picker>
              </div>
              <div class="text">下班:</div>
              <div>
                <el-time-picker class="time-input" size="medium" v-model="timeObj.endTime" format="HH:mm" :picker-options="{selectableRange:timeObj.endTimeRange}" 
                  :clearable="false" :editable="false" @change="timeChange('endTime',index)">
                </el-time-picker>
              </div>
            </div>
            <div class="classes-way-item" :key="'timeValid_'+index">
              <div style="width:60px;margin-right:30px"></div>
              <div class="text">最早打卡时间:</div>
              <div>
                <el-time-picker class="time-input" size="medium" v-model="timeObj.earlyTime" format="HH:mm" :picker-options="{selectableRange:timeObj.earlyTimeRange}" 
                  :editable="false" @change="timeChange('earlyTime',index)">
                </el-time-picker>
              </div>
              <div class="text">最晚打卡时间:</div>
              <div>
                <el-time-picker class="time-input" size="medium" v-model="timeObj.lateTime" format="HH:mm" :picker-options="{selectableRange:timeObj.lateTimeRange}" 
                  :editable="false" @change="timeChange('lateTime',index)">
                </el-time-picker>
              </div>
            </div>
          </template>
          <div v-if="classesForm.timeType===1" class="classes-way-item">
            <div style="width:60px;margin-right:30px;padding-top:8px">
              <el-checkbox v-model="classesForm.isNeedRest" size="medium" :true-label="1" :false-label="0" @change="checkChange">休息</el-checkbox>
            </div>
            <div class="text">休息开始:</div>
            <div>
              <el-time-picker class="time-input" size="medium" v-model="classesForm.restStartTime" format="HH:mm" :clearable="false" :editable="false"
                :picker-options="{selectableRange:classesForm.restTimeRange.start}" @change="timeChange('restStartTime')">
              </el-time-picker>
            </div>
            <div class="text">休息结束:</div>
            <div>
              <el-time-picker class="time-input" size="medium" v-model="classesForm.restEndTime" format="HH:mm" :clearable="false" :editable="false"
                :picker-options="{selectableRange:classesForm.restTimeRange.end}" @change="timeChange('restEndTime')">
              </el-time-picker>
            </div>
          </div>
        </div>
        <div style="margin-bottom:20px">
          <span>合计工作时长{{workTime}}</span>
          <span style="color:#c4c4c4">（考勤统计工作时长及请假统计，会以此时间为准）</span>
        </div>
        <div style="text-align:center">
          <el-button size="medium" type="primary" @click="ensure">
            <span v-if="type==='add'">保存</span>
            <span v-else>修改</span>
          </el-button> 
          <el-button size="medium" type="danger" @click="cancel">取消</el-button>
        </div>
      </template>
    </div>
  `;

  return {
    props: {
      classes: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        required: true
      }
    },

    computed: {
      workTime: function () {
        var classesForm = this.classesForm;
        if (classesForm === null) {
          return '';
        }
        var workTime = classesForm.workTime;
        var hour = Math.floor(_.round(workTime / 60, 2));
        var minute = workTime % 60;
        return `${hour}小时${minute}分钟`;
      }
    },

    data: function () {
      return {
        loading: false,
        classesForm: null,
        timeWayList: ClassFormModel.timeWayList
      };
    },

    created: function () {
      this.initData();
    },

    methods: {
      initData: function () {
        var type = this.type;
        if (type === 'add') {
          this.classesForm = new ClassFormModel();
          return;
        }

        var classes = this.classes;
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/getAttendClassTail', {
          classId: classes.id
        }).then(function (validTimeList) {
          var validTimeObj = {};
          for (var i = 0; i < validTimeList.length; i++) {
            var validTime = validTimeList[i];
            var baseCheckTime = validTime.baseCheckTime;
            baseCheckTime = ClassFormModel.getTimeStr(baseCheckTime);
            var obj = {
              baseCheckTime: baseCheckTime,
              earlyTime: null,
              lateTime: null
            };

            var earlyTime = validTime.baseCheckStartTime;
            if (earlyTime !== null) {
              obj.earlyTime = ClassFormModel.getTimeStr(earlyTime);
            }

            var lateTime = validTime.baseCheckEndTime;
            if (lateTime !== null) {
              obj.lateTime = ClassFormModel.getTimeStr(lateTime);
            }

            validTimeObj[baseCheckTime] = obj;
          }

          self.classesForm = new ClassFormModel(classes, validTimeObj);
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      timeTypeChange: function () {
        this.classesForm.resetTimeList();
      },

      timeChange: function (type, index) {
        var classesForm = this.classesForm;
        classesForm.resetTimeRange(type, index);

        if (['startTime', 'endTime', 'restStartTime', 'restEndTime'].indexOf(type) !== -1) {
          classesForm.calWorkTime();
        }
      },

      checkChange: function () {
        this.classesForm.calWorkTime();
      },

      ensure: function () {
        var code = this.classesForm.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`attendance.classesSetting.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        var type = this.type;
        if (type === 'add') {
          this.addClasses();
        } else {
          this.updateClasses();
        }
      },

      addClasses: function () {
        var postData = this.classesForm.getObject();
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/insertClass', postData).then(function (id) {
          return self.saveValidTime(id).then(function () {
            self.$alert('新增班次成功', '信息', {
              callback: function () {
                self.$emit('save-success');
              }
            });
            self.loading = false;
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateClasses: function () {
        var postData = this.classesForm.getObject();
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/updateClass', postData).then(function () {
          return self.saveValidTime(postData.id).then(function () {
            self.$alert('修改班次成功', '信息', {
              callback: function () {
                self.$emit('save-success');
              }
            });
            self.loading = false;
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      saveValidTime: function (id) {
        var postData = this.classesForm.getValidObject(id);
        return ajaxRequest('dingTalk/insertAttendClassTail', postData).then(function (msg) {
          return msg;
        });
      },

      cancel: function () {
        this.$emit('close');
      }
    },

    template: template
  };
}();
